package com.smsc.headend.connector.service.impl;

import cn.hutool.core.util.StrUtil;
import com.smsc.headend.common.utils.RedisKeys;
import com.smsc.headend.common.utils.RedisUtils;
import com.smsc.headend.connector.service.TaskService;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.ConnectorTask;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    public static final String CONNECTOR_EXECUTING_ATOMICTASK = "connector:executing:atomictask:";
    //    Cache<String, ConnectorTask> atomicTaskCache = CacheBuilder.newBuilder()
//            //设置缓存容器的初始容量为10
//            .initialCapacity(1000)
//            // maximumSize 设置缓存大小
//            //设置并发级别为20，并发级别是指可以同时写缓存的线程数
//            .concurrencyLevel(200)
//            // expireAfterWrite设置写缓存后60s过期
//            .expireAfterWrite(30, TimeUnit.SECONDS)
//            //设置缓存的移除通知
//            .build();

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean addAtomicTask(ConnectorTask connectorTask) {
        return redisTemplate.opsForValue().setIfAbsent(CONNECTOR_EXECUTING_ATOMICTASK + connectorTask.getAtomicTaskNo(), 1, 3, TimeUnit.SECONDS);
    }

    @Override
    public void removeAtomicTaskKey(String atomicTaskNo) {
        log.debug("remove redis key {}", atomicTaskNo);
        redisUtils.del(CONNECTOR_EXECUTING_ATOMICTASK + atomicTaskNo);
    }

    @Override
    public void refreshAtomicTaskNo(Long comId, String taskNo, String atomicTaskNo, byte[] wrappedNextRequest) {
        redisUtils.set(RedisKeys.getCONAtomicTaskStatusKey(comId), taskNo + ":" + atomicTaskNo, 60);
//        atomicTaskCache.put(atomicTaskNo, new byte[][]{wrappedNextRequest});
    }

    @Override
    public boolean isTaskExist(ConnectorTask connectorTask) {
        Object packets = redisUtils.get(CONNECTOR_EXECUTING_ATOMICTASK + connectorTask.getAtomicTaskNo());
        if (packets == null) {
            return false;
        }

        String comingTaskPacket = ByteUtils.byteToHexString(connectorTask.getPacketBytes()[0]).replaceAll(" ", "");
        String packetInRedis = StrUtil.toString(packets);
        log.debug("comming={}, redis={}", ByteUtils.byteToHexString(connectorTask.getPacketBytes()[0]), packetInRedis);
        return comingTaskPacket.equals(packetInRedis);
    }

}
